package com.controller;

import com.MyTask.CovidTask;
import com.entity.User;
import com.service.MyCipher;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class MainController {
    private MyCipher myCipher;
    private UserService userService;

    @Autowired
    public MainController(MyCipher myCipher, UserService userService) {
        this.myCipher = myCipher;
        this.userService = userService;
    }

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("publicKey", myCipher.getPublicKey());
        return "home";
    }

    @PostMapping("/submit")
    //返回值以特定格式(字符串，json)写到response 的body,返回客户端
    @ResponseBody
    public String submit(@RequestParam("action") String value, @RequestParam("id") String id, @RequestParam("password") String password) throws Exception {
        id = myCipher.decrypt(id);
        password = myCipher.decrypt(password);
        if (value.equals("submit")) {
            User user = userService.getUser(id);
            if (user != null)
                return "failed,already submit";
                if (!CovidTask.test(id, password)) {
                    return "login failed,check your id and password";
                }
                userService.addUser(id, password);
                return "submit success!";

        } else if (value.equals("cancel")) {
            if (userService.deleteUser(id, password) != 0) {
                return "cancel success！";
            } else {
                return "cancel failed,check your id and password！";
            }
        }
        return "unknown error";
    }
}

